/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Anthony
 */
class puzzlePieces {
    //values for rows and columns
    public int ROWS = 4;
    public int COLS = 4;
    private Btn[][] theButtons;
    private Btn theBlankOne;

    //Setting up the 2d array
    public puzzlePieces() {
        theButtons = new Btn[ROWS][COLS];
        //Scrambles
        reset();
    }

    //getting the number on the buttons
    String getButtonNum(int row, int col) {
        return theButtons[row][col].getNum();
    }

    //Resetting
    public void reset() {
        for (int r = 0; r < ROWS; r++) {
            for (int c = 0; c < COLS; c++) {
                theButtons[r][c] = new Btn(r, c, "" + (r * COLS + c + 1));
            }
        }
        //Makes the last button the "?" or "blank" one
        theBlankOne = theButtons[ROWS - 1][COLS - 1];
        theBlankOne.setNum(null);
        for (int r = 0; r < ROWS; r++) {
            for (int c = 0; c < COLS; c++) {
                moveButtons(r, c, (int) (Math.random() * ROWS), (int) (Math.random() * COLS));
            }
        }
    }

    //Returns a true or false to be used in puzzleGUI. Decides if it can move or not
    public boolean moveTile(int r, int c) {
        return isBlank(r, c, -1, 0) || isBlank(r, c, 1, 0)
                || isBlank(r, c, 0, -1) || isBlank(r, c, 0, 1);
    }

    //Returns true or false for above
    private boolean isBlank(int r, int c, int adjR, int adjC) {
        int nearRow = r + adjR;
        int nearColumn = c + adjC;
        //Checks to see if it can move to the space (the blank one)
        if (nearRowCol(nearRow, nearColumn)
                && theButtons[nearRow][nearColumn] == theBlankOne) {
            moveButtons(r, c, nearRow, nearColumn);
            return true;
        }
        return false;
    }

    //Returns true or false when called up there
    public boolean nearRowCol(int r, int c) {
        return r >= 0 && r < ROWS && c >= 0 && c < COLS;
    }
    //Switches the buttons

    private void moveButtons(int r1, int c1, int r2, int c2) {
        Btn temp = theButtons[r1][c1];
        theButtons[r1][c1] = theButtons[r2][c2];
        theButtons[r2][c2] = temp;
    }
    //TODO: Gameover stuff
}

class Btn {

    int buttonRow;
    int buttonCol;
    String buttonNum;

    public Btn(int row, int col, String num) {
        buttonRow = row;
        buttonCol = col;
        buttonNum = num;
    }

    public void setNum(String newNum) {
        buttonNum = newNum;
    }

    public String getNum() {
        return buttonNum;
    }
}
